package com.helpdesk.controllers;

import com.helpdesk.beans.CategoriesFacade;
import com.helpdesk.beans.CategoriesLazyModel;
import com.helpdesk.controllers.util.JsfUtil;
import com.helpdesk.entities.Categories;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.UploadedFile;

@ManagedBean(name = "categoriesController")
@SessionScoped
public class CategoriesController implements Serializable {

    private Categories current;
    private List<Categories> items = null;
    @EJB
    private com.helpdesk.beans.CategoriesFacade ejbFacade;
    private int selectedItemIndex;
    private LazyDataModel<Categories> cats;

    public CategoriesController() {
    }

    public Categories getSelected() {
        if (current == null) {
            current = new Categories();
            selectedItemIndex = -1;
        }
        return current;
    }

    public void setSelected(Categories cat) {
        current = cat;
    }

    public List<Categories> getItems() {
        if (items == null) {
            items = ejbFacade.findAll();
        }
        return items;
    }

    public void setItems(List<Categories> items) {
        this.items = items;
    }

    public LazyDataModel<Categories> getCats() {
        if (cats == null) {
            cats = new CategoriesLazyModel(getFacade().findAll());
        }
        return cats;
    }

    public void setCats(LazyDataModel<Categories> cats) {
        this.cats = cats;
    }

    private CategoriesFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {

        return "list_category";
    }

    public String prepareView() {
        return "view_category";
    }

    public String prepareCreate() {
        current = new Categories();
      
        return "new_category";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage("Add new category is success!");
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Add new category is not success!");

            return null;
        }
    }

    public String prepareEdit() {
        return "edit_category";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CategoriesUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        performDestroy();
        return "List";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            RequestContext requestContext = RequestContext.getCurrentInstance();
            requestContext.addCallbackParam("item",current.getId());
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CategoriesDeleted"));

        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public void handleFileUpload(FileUploadEvent event) {
        try {
            UploadedFile _uploadedFile = event.getFile();
            String fileName = JsfUtil.saveImageFile(_uploadedFile);
            current.setIcon(fileName);
            FacesMessage msg = new FacesMessage("Succesful", fileName + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileUploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileUploadController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @FacesConverter(forClass = Categories.class)
    public static class CategoriesControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CategoriesController controller = (CategoriesController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "categoriesController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Categories) {
                Categories o = (Categories) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Categories.class.getName());
            }
        }
    }
}
